<?php

/**
 * This is the model class for table "usuario".
 *
 * The followings are the available columns in table 'usuario':
 * @property integer $id
 * @property integer $perfil_id
 * @property string $usuario
 * @property string $senha
 * @property string $email
 * @property string $nome
 * @property string $endereco
 * @property integer $telefone
 */
class Usuario extends CActiveRecord
{

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'usuario';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('perfil_id, usuario, senha, email', 'required'),
            array('perfil_id, telefone', 'numerical', 'integerOnly' => true),
            
            array('usuario', 'length', 'min' => 4, 'max' => 16),
            array('usuario', 'unique', 'message' => 'Esse usuário já existe'),
            
            array('senha', 'length', 'min' => 8, 'max' => 255),
            
            array('email', 'length', 'max' => 200),
            array('email', 'unique', 'message' => 'Esse e-mail já está em uso'),
            array('email', 'email'),
            
            array('nome, endereco', 'length', 'max' => 255),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, perfil_id, usuario, senha, email, nome, endereco, telefone', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'perfil' => array(self::BELONGS_TO, 'Perfil', 'perfil_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'perfil_id' => 'Perfil',
            'usuario' => 'Usuario',
            'senha' => 'Senha',
            'email' => 'E-mail',
            'nome' => 'Nome',
            'endereco' => 'Endereco',
            'telefone' => 'Telefone',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('perfil_id', $this->perfil_id);
        $criteria->compare('usuario', $this->usuario, true);
        $criteria->compare('senha', $this->senha, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('nome', $this->nome, true);
        $criteria->compare('endereco', $this->endereco, true);
        $criteria->compare('telefone', $this->telefone);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Usuario the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * Cria um hash da senha usando as novas funções do PHP
     * 
     * @param string $senha
     * @return string
     */
	 
	
    public static function hashSenha($senha)
    {
        return CPasswordHelper::hashPassword($senha);
    }

    /**
     * Verifica a senha passada com o hash anteriormente gerado
     * 
     * @param string $senha
     * @param string $hash
     * @return boolean
     */
    public static function verifySenha($senha, $hash)
    {
        return CPasswordHelper::verifyPassword($senha, $hash);
    }

    /**
     * É chamado me uma consulta para dizer que modelo deverá tratar o resultado
     *
     * @param array $attributes
     * @return Usuario
     */
    protected function instantiate($attributes)
    {
        switch ($attributes['perfil_id']) {
            case 3:
                $className = 'UsuarioProfessor';
                break;
            case 4:
                $className = 'UsuarioAluno';
                break;
            case 5:
                $className = 'UsuarioEmpresa';
                break;
            case 6:
                $className = 'UsuarioAdministrador';
                break;
            case 7:
                $className = 'UsuarioOrientador';
                break;
            case 8:
                $className = 'UsuarioProfessorEstagio';
                break;
            default:
                throw CHttpException('Tipo de usuário desconhecido');
        }

        return new $className(null);
    }
    
    protected function beforeSave()
    {
      if ($this->isNewRecord) {
            $this->senha = self::hashSenha($this->senha);
      }
      return parent::beforeSave();
    }
}
